import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LayoutComponent } from "../../../global/layout/layout.component";
import { WclService } from "./wcl.service";
import { FormGroup, FormControl } from '@angular/forms';
import { environment } from '../../../../../environments/environment';
import { AppPaginationComponent, PaginationModel } from "../../../../widgets/pagination/pagination.component";
import { otmRequireFile } from '../../../../../assets/config/filerequire';
import { DataService } from '../../../../services/data.service';
import * as moment from 'moment';
import * as _ from 'lodash';
import { Util } from 'app/common/util';

@Component({
  selector: 'app-wcl',
  templateUrl: './wcl.component.html',
  styleUrls: ['./wcl.component.scss'],
  providers: [WclService]
})
export class WclComponent implements OnInit {
  // lodash
  public _: any = _;

  // 获取附件数据
  public fileData: any;

  // 存放提示信息
  public requireTips: any = [];

  // 备案机构、受托人、托管人
  public distionary: any = {
    RECORDORG_TYPE: [],  // 备案机构
    LINK_PRINCIPAL_NO: [],   //受托人
    TRUSTEE: []   //  托管人
  }

  // 存放提示信息字符串
  public requireFinalTips: any;

  // 存放提示信息字符串
  public requireFinalPdfTips: any;

  // 存放提示信息字符串
  public requireFinalWordTips: any;
  // 存放未上传pdf提示信息

  public requirePdfTips: any = [];

  // 存放未上传word提示信息
  public requireWordTips: any = [];

  // filerequired的返回值
  public fileReturnValue: any;

  // 已勾选的nFundNo
  public selectednFundNo;



  // 字典值
  public dictionaryList: any = {
    STOP_TYPE: []
  };
  // 菜单数据
  public menuData: any;
  // 菜单按钮集合
  public menuResourceSet: any;

  //  托管人数据
  // public bankDictionaryList = [];

  // 产品业务类型,修改(1)、续约(2)、终止(3)、开始运作(4)
  public businessType: any;

  // 一对多单个产品信息
  public otmProductBody: any = {};
  //查询分页列表post数据
  public getOnetomanyPost = {
    pageIndex: 1,
    pageSize: 10,
    sFullName: '',
    sFundCode: '',
    sFundStatus: 1,
    sStatusRunning: '',
    sTrustee: ''
  };
  //一对多分页配置
  public onetomanyListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //一对多分页列表list
  public onetomanyList = [];
  // 列表是否全选
  public isCheckedAll: boolean = false;
  // 用于开始运作录入时对比有无修改
  public checkBody: any;
  constructor(
    public router: Router,
    public layoutComponent: LayoutComponent,
    public wclService: WclService,
    public dataservice: DataService
  ) {
    this.list();
  }

  ngOnInit() {
    let that = this;
    sessionStorage.setItem('otm_isStop', 'isnoStop');
    // 权限处理
    this.dataservice.initTree.subscribe((data) => {
      let SessionMenuData = sessionStorage.getItem('menu');
      this.menuData = JSON.parse(SessionMenuData)
      this.menuResourceSet = [];
      _.forEach(this.menuData, (item, index) => {
        if (item.sName == '一对多专户') {
          _.forEach(item.children, (it, idx) => {
            if (it.sName == '未成立') {
              that.menuResourceSet = it.resourceSet
              sessionStorage.setItem('btn-otm', that.menuResourceSet);
            }
          })
        }
      })
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '一对多专户') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '未成立') {
            that.menuResourceSet = it.resourceSet
            sessionStorage.setItem('btn-otm', that.menuResourceSet);
          }
        })
      }
    })
    this.getDictionary();
    // 获取托管人数据
    // this.bankDictionaryList = JSON.parse(localStorage.getItem("bankDictionaryList"));
  }
  ngAfterViewInit() {
    let that = this;
    // 多选下拉框
    window['$'](".select2").select2();
    window['$']('#sTrusteeSelected').select2({ width: '182px', tags: true });
    window['$']('#sTrusteeSelected').on("select2:select", function (e) {
      that.getOnetomanyPost.sTrustee = window['$']('#sTrusteeSelected').select2("val");
    })
  }

  create() {
    sessionStorage.setItem('currentTitle', "创设·一对多");
    this.layoutComponent.nav(null, null, "创设·一对多");
    this.router.navigate(['pages/onetomany/new/detail/add']);
  }
  // 查询分页列表
  list(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getOnetomanyPost.sFullName = _.trim(this.getOnetomanyPost.sFullName);
    this.getOnetomanyPost.sFundCode = _.trim(this.getOnetomanyPost.sFundCode);
    this.getOnetomanyPost.sTrustee = _.trim(this.getOnetomanyPost.sTrustee);
    this.getOnetomanyPost.pageIndex = pageNum ? pageNum : this.onetomanyListPageInfo.currentPageNum;
    this.getOnetomanyPost.pageSize = pageSize ? pageSize : this.onetomanyListPageInfo.pageSize;
    this.wclService.list(this.getOnetomanyPost).subscribe(data => {
      if (data) {
        that.onetomanyList = data.list;
        that.onetomanyListPageInfo.currentPageNum = data.pageNum;
        that.onetomanyListPageInfo.totalPages = data.pages;
        that.onetomanyListPageInfo.total = data.total;
        that.onetomanyListPageInfo.startRow = data.startRow;
        that.onetomanyListPageInfo.endRow = data.endRow;
      }
      // // 给表格列支持列拖动效果
      // setTimeout(() => {
      //   Util.colResizable("#fixed-table");
      // }, 100);

      // 给表格列支持列拖动和固定表头效果
      Util.colResizable("#wclList");
    });
  }
  // 个数分页
  onetomanypageSizeChange(pageSize: number) {
    if (pageSize !== this.onetomanyListPageInfo.pageSize) {
      this.onetomanyListPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 页码分页
  onetomanyPageNavigation(currentPageNum: number) {
    this.onetomanyListPageInfo.currentPageNum = currentPageNum;
    this.list(this.onetomanyListPageInfo.currentPageNum, this.onetomanyListPageInfo.pageSize);
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.onetomanyList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.onetomanyList, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.onetomanyList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.onetomanyList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }

  // 判断合同期限
  IsContractPeriod() {
    if (this.otmProductBody.sIsContractPeriod == "1") {
      this.otmProductBody.nContractPeriod = "";
      window['$']('#nContractPeriod').attr("disabled", "disabled");
      window['$']('#nContractPeriod').css("background", "#eee");
    }
    if (this.otmProductBody.sIsContractPeriod == "0") {
      window['$']('#nContractPeriod').removeAttr("disabled", "disabled");
      window['$']('#nContractPeriod').css("background", "#ffffff");
    }
  }


  // 开始运作按钮
  goRunning() {
    let that = this;
    // 开始运作勾选产品
    let checkProduct = [];
    this.otmProductBody = {};
    _.forEach(this.onetomanyList, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    if (checkProduct.length == 1) {
      this.selectednFundNo = checkProduct[0].nFundNo
      this.businessType = "4";
      this.wclService.checkProductStatus(checkProduct[0].nFundNo, this.businessType).subscribe(data => {
        if (data == true) {
          window['swal']("提示", "该产品正在运作审核中...", "warning");
        } else {
          that.wclService.otmGetSingleProduct(checkProduct[0].nFundNo).subscribe(data => {
            if (data) {
              that.otmProductBody = data;
              // 用于开始运作录入时对比有无修改
              that.checkBody = _.clone(data);
              that.IsContractPeriod();
              that.fileRequired();
              window['$']("#runProduct").modal('show');
            }
          })
        }
      })
    } else {
      window['swal']("提示", "请选择一个产品进行开始运作操作", "warning")
    }
  }

  // 产品开始运作
  productRunning() {
    let that = this;
    // 产品业务类型,修改(1)、续约(2)、终止(3)、开始运作(4)
    this.businessType = "4";
    if (that.fileTip()) {
      //开始运作填写字段必填校验
      if (that.requiredRunning()) {
        //日期大小校验
        if (that.beforeRunTime()) {
          // 判断数据有无修改
          if (Util.objectCheck(that.checkBody, that.otmProductBody)) {
            window['swal']("提示", "信息未修改，不会生成修改审核记录", "warning");
            window['$']("#runProduct").modal('hide');
          } else {
            window["swal"]({
              title: "提示",
              text: "是否确定开始运作操作?",
              type: "warning",
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              showCancelButton: true,
              closeOnConfirm: false,
              closeOnCancel: true,
              showLoaderOnConfirm: true
            },
              function (isConfirm) {
                if (isConfirm) {
                  delete that.otmProductBody.sTrusteeZh;
                  delete that.otmProductBody.sFundCategoryZh;
                  delete that.otmProductBody.sSalesChannels;
                  delete that.otmProductBody.nValueDecZh;
                  delete that.otmProductBody.sIsHandZh;
                  that.wclService.operationType(that.otmProductBody, that.businessType).subscribe(data => {
                    if (data) {
                      window['swal']("成功", "请等待产品审核!", "success");
                      window['$']("#runProduct").modal('hide');
                    }
                  })
                }
              })
          }
        } else {
          window['swal']("提示", "到期日不能比起始运作日期早", "warning");
        }
      }
    }
  }

  // 开始运作必填校验
  requiredRunning() {
    let that = this;
    let requiredRunTip = [];
    let sFundCode = _.trim(this.otmProductBody.sFundCode);
    if (sFundCode == "" || sFundCode == null) {
      requiredRunTip.push("产品代码");
    }
    if (this.otmProductBody.dBegin == "" || this.otmProductBody.dBegin == null) {
      requiredRunTip.push("起始运作日期");
    }
    if (this.otmProductBody.sIsContractPeriod == '0' && (this.otmProductBody.dEnd == "" || this.otmProductBody.dEnd == null)) {
      requiredRunTip.push("到期日");
    }
    if (requiredRunTip.length > 0) {
      let requiredRunTips = requiredRunTip.join("、");
      window['swal']("提示", "请填写:" + requiredRunTips, "warning");
      return false;
    } else {
      return true;
    }
  }

  // (起始运作日期/到期日)-校验
  beforeRunTime() {
    if (this.otmProductBody.dBegin !== "" && this.otmProductBody.dBegin !== null && this.otmProductBody.dEnd !== "" && this.otmProductBody.dEnd !== null) {
      if (this.otmProductBody.dBegin == this.otmProductBody.dEnd) {
        return true;
      } else {
        if (moment(this.otmProductBody.dBegin).isBefore(this.otmProductBody.dEnd)) {
          return true;
        } else {
          return false;
        }
      }
    } else {
      return true;
    }
  }
  // 删除产品
  delProduct() {
    let that = this;
    let checkedItem = [];
    let checkedFundName = [];
    _.forEach(that.onetomanyList, item => {
      if (item.isChecked == true) {
        checkedItem.push(item.nFundNo);
        checkedFundName.push(item.sFundName);
      }
    })
    let checkedTips = checkedFundName.join("、");
    if (checkedItem.length > 0) {
      window['swal']({
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        title: "提示",
        text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否删除产品：" + checkedTips + "</div>",
        html: true
      }, function (isConfirm) {
        if (isConfirm) {
          let putBody: any = {
            "nFundNos": checkedItem
          }
          that.wclService.del(putBody).subscribe(data => {
            if (data) {
              window['swal']("删除成功！", "", "success")
              that.list();
            }
          })
        }
      });
    }
    else {
      window['swal']("提示", "请选择一个或多个产品进行删除", "warning")
    }
  }
  // 导出
  exportExcel() {
    let that = this;
    let checkedItem = [];
    _.forEach(that.onetomanyList, item => {
      if (item.isChecked == true) {
        checkedItem.push(item.nFundNo);
      }
    })
    let converItem = checkedItem.join(',');
    let getBody = {
      "nFundNoList": converItem,
      "sFundStatus": this.getOnetomanyPost.sFundStatus,
      "sFullName": this.getOnetomanyPost.sFullName,
      "sFundCode": this.getOnetomanyPost.sFundCode,
      "sStatusRunning": this.getOnetomanyPost.sStatusRunning,
      "sTrustee": this.getOnetomanyPost.sTrustee
    }
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    //  转码，兼容ie
    getBody.sFullName = encodeURI(getBody.sFullName)
    getBody.sTrustee = encodeURI(getBody.sTrustee)
    getBody.sFundCode = encodeURI(getBody.sFundCode)
    iframe.attr('src', environment.server + '/pms/v1/onetomany/export/oneToManyFundInfoList?token=' + sessionStorage.getItem('token') + '&nFundNoList=' + getBody.nFundNoList + '&sFundStatus=' + getBody.sFundStatus + '&sFullName=' + getBody.sFullName + '&sFundCode=' + getBody.sFundCode + '&sStatusRunning=' + getBody.sStatusRunning + '&sTrustee=' + getBody.sTrustee);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }
  // 切换产品状态
  changeProductStatus(type, item) {
    let that = this;
    if (type == 'stop') {
      window["swal"]({
        title: "提示",
        text: "是否将产品状态更改为暂停",
        type: "warning",
        confirmButtonText: "确认",
        confirmButtonColor: "#DD6B55",
        cancelButtonText: "取消",
        showCancelButton: true,
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
        function (isConfirm) {
          if (isConfirm) {
            that.wclService.changeProductStatus(item.nFundNo, 'stop').subscribe(data => {
              if (data) {
                window["swal"]("成功", "产品停止运行!", "success");
                that.list();
              }
            })
          }
        })
    }
    if (type == 'run') {
      window["swal"]({
        title: "提示",
        text: "是否将产品状态更改为运行",
        type: "warning",
        confirmButtonText: "确认",
        confirmButtonColor: "#DD6B55",
        cancelButtonText: "取消",
        showCancelButton: true,
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
        function (isConfirm) {
          if (isConfirm) {
            that.wclService.changeProductStatus(item.nFundNo, 'run').subscribe(data => {
              if (data) {
                window["swal"]("成功", "产品开始运行!", "success");
                that.list();
              }
            })
          }
        })
    }
  }
  edit(type, item?) {
    let that = this;
    sessionStorage.setItem('parentIndex', 'wcl');
    // 产品修改勾选
    let checkProduct = [];
    switch (type) {
      case 'dbclick':
        sessionStorage.setItem('currentTitle', "详情·未成立·一对多");
        that.layoutComponent.nav(null, null, "详情·未成立·一对多");
        that.router.navigate(['pages/onetomany/wcl/detail/edit/' + item.nFundNo]);
        break;
      case 'one':
        _.forEach(that.onetomanyList, it => {
          if (it.isChecked == true) {
            checkProduct.push(it);
          }
        })
        if (checkProduct.length == 1) {
          sessionStorage.setItem('currentTitle', "详情·未成立·一对多");
          that.layoutComponent.nav(null, null, "详情·未成立·一对多");
          that.router.navigate(['pages/onetomany/wcl/detail/edit/' + checkProduct[0].nFundNo]);
        } else {
          window['swal']("提示", "请选择一个产品进行查看", "warning");
        }
        break;
    }
  }
  // 计算合同到期日
  countMonth() {
    if (this.otmProductBody.dBegin && this.otmProductBody.nContractPeriod) {
      this.otmProductBody.dEnd = moment(this.otmProductBody.dBegin).add(this.otmProductBody.nContractPeriod, 'months').format('YYYY-MM-DD')
    } else {
      this.otmProductBody.dEnd = '';
    }
  }

  // 校验文件是否已经上传
  fileRequired() {
    let that = this;

    let getBody = {
      "sFundType": 2,
      "nFundNo": this.selectednFundNo
    }
    this.wclService.getFileTree(getBody).subscribe((data) => {
      if (data) {
        this.requirePdfTips = [];
        this.requireTips = [];
        this.requireWordTips = [];

        this.fileData = data.subTree
        // 获取配置文件
        let requireFile = otmRequireFile.requireFile;
        // 存放要求上传的类别
        let requireType: any = [];
        // 校验是否有上传
        _.forEach(requireFile, (item) => {
          requireType.push(item.sAttachType);
        })

        _.forEach(requireType, (item, index) => {
          _.forEach(this.fileData, (it, index) => {
            _.forEach(it.subTree, (i, index) => {
              if (item == i.sAttachType) {
                if (i.fileList[0].nAttachNo == null) {
                  this.requireTips.push(item);
                }
              }
            })
          })
        })

        // 校验pdf
        // 获取配置文件
        let requirePdfFile = otmRequireFile.requirePdfAndWord;
        // 存放要求上传的类别
        let requirePdfType: any = [];
        // 存放切出来的附件后缀
        let rawPdfFormat: any = [];

        _.forEach(requirePdfFile, (item, index) => {
          _.forEach(this.fileData, (it, index) => {
            _.forEach(it.subTree, (i, index) => {
              if (item.sAttachType == i.sAttachType) {
                if (i.fileList[0].nAttachNo !== null) {
                  rawPdfFormat = [];
                  _.forEach(i.fileList, (f, idx) => {

                    // 切后缀放进数组
                    // 附件名长度
                    let len = f.sAttachName.length;
                    // 最后一个.的位置
                    let lastDotIndex = f.sAttachName.lastIndexOf(".");
                    let index;
                    let fileType = f.sAttachName.substring(lastDotIndex + 1, len + 1);
                    rawPdfFormat.push(fileType);
                  })
                  if (_.includes(rawPdfFormat, 'pdf') !== true) {
                    //  没有该格式
                    this.requirePdfTips.push(item.sAttachType);
                  }

                } else {
                  // 如果没附件的话，加提示。
                  this.requirePdfTips.push(item.sAttachType);
                }
              }
            })
          })
        })

        // 校验word
        // 获取配置文件
        let requireWordFile = otmRequireFile.requirePdfAndWord;
        // 存放要求上传的类别
        let requireWordType: any = [];
        // 存放切出来的附件后缀
        let rawWordFormat: any = [];
        _.forEach(requireWordFile, (item, index) => {
          _.forEach(this.fileData, (it, index) => {
            _.forEach(it.subTree, (i, index) => {
              if (item.sAttachType == i.sAttachType) {
                if (i.fileList[0].nAttachNo !== null) {
                  rawWordFormat = [];
                  _.forEach(i.fileList, (f, idx) => {
                    // 切后缀放进数组
                    // 附件名长度
                    let len = f.sAttachName.length;
                    // 最后一个.的位置
                    let lastDotIndex = f.sAttachName.lastIndexOf(".");
                    let index;
                    let fileType = f.sAttachName.substring(lastDotIndex + 1, len + 1);
                    rawWordFormat.push(fileType);
                  })
                  if (_.includes(rawWordFormat, 'docx') !== true && _.includes(rawWordFormat, 'doc') !== true) {
                    //  没有该格式
                    this.requireWordTips.push(item.sAttachType);
                  }
                }
                else {
                  // 如果没附件的话，加提示。
                  this.requireWordTips.push(item.sAttachType);
                }
              }
            })
          })
        })
      }
    })
  }
  //文件上传缺失提示
  fileTip() {
    // 优化提示信息：
    this.requireFinalTips = '';
    this.requireFinalPdfTips = '';
    this.requireFinalWordTips = '';
    if (this.requireTips.length !== 0) {
      this.requireFinalTips = '请上传：' + this.requireTips.join('、') + '文件；'
    }
    if (this.requirePdfTips.length !== 0) {
      this.requireFinalPdfTips = '请上传：' + this.requirePdfTips.join('、') + '的pdf格式文件；'
    }
    if (this.requireWordTips.length !== 0) {
      this.requireFinalWordTips = '请上传：' + this.requireWordTips.join('、') + '的word格式文件；'
    }
    if (this.requireTips.length == 0 && this.requirePdfTips.length == 0 && this.requireWordTips.length == 0) {
      return true;
    }
    else {
      window['swal']({
        title: "提示",
        text: this.requireFinalPdfTips + '<br>' + this.requireFinalWordTips + '<br>' + this.requireFinalTips + '<br>请联系投资发展部传完以上文件，产品才能切换到已成立状态',
        html: true,
        type: "warning"
      });
      return false;
    }
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.onetomanyList, [colName], ["asc"]);
    if (JSON.stringify(this.onetomanyList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.onetomanyList, [colName], ["desc"]);
    }
    this.onetomanyList = listDataAsc;
  }
  // 获取备案机构、受托人、托管人下拉框值
  getDictionary() {
    let that = this;
    this.wclService.getDictionary().subscribe(data => {
      if (data) {
        that.distionary.RECORDORG_TYPE = data.RECORDORG_TYPE;
        that.distionary.LINK_PRINCIPAL_NO = data.LINK_PRINCIPAL_NO;
        that.distionary.TRUSTEE = data.TRUSTEE;
      }
    })
  }

}

